package cn.tedu.blog.server.service.impl;

import cn.tedu.blog.server.exception.ServiceException;
import cn.tedu.blog.server.mapper.ArticleTagMapper;
import cn.tedu.blog.server.mapper.TagMapper;
import cn.tedu.blog.server.pojo.dto.TagAddNewDTO;
import cn.tedu.blog.server.pojo.entity.Tag;
import cn.tedu.blog.server.pojo.vo.TagDetailVO;
import cn.tedu.blog.server.pojo.vo.TagListItemVO;
import cn.tedu.blog.server.repo.ITagRepository;
import cn.tedu.blog.server.service.ITagService;
import cn.tedu.blog.server.utils.JsonPage;
import cn.tedu.blog.server.utils.ServiceCode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import static cn.tedu.blog.server.repo.ITagRepository.KEY_PREFIX_Tag_ITEM;


@Slf4j
@Service
public class TagServiceImpl implements ITagService {
    @Autowired
    private TagMapper tagMapper;
    @Autowired
    private ArticleTagMapper articleTagMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ITagRepository tagRepository;

    @Override
    public List<TagDetailVO> select() {
        log.debug("正在执行tag标签列表查询");
       List<TagDetailVO> list = tagMapper.select();
        return list;
    }
    @Override
    public void addNew(TagAddNewDTO tagAddNewDTO) {
        log.info("开始处理增加标签的业务,参数,{}",tagAddNewDTO);
        String name=tagAddNewDTO.getName();
        int count=tagMapper.countByName(name);
        if (count>0){
            String message="创建标签失败,【" + name + "】已经被占用！";
            log.info(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        if (name.equals("") || name.equals(" ") || name == null) {
            String message = "标签名字不能为空格或字符串";
            log.info(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        char[] countName = name.toCharArray();
        System.out.println(countName);
        for (int i = 0; i < countName.length; i++) {
            if (countName[i] == ' ') {
                String message = "标签名字不能为空格或字符串";
                log.info(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }
        // 创建实体对象（Mapper的方法的参数是实体类型）
        Tag tag=new Tag();

        // 将当前方法参数的值复制到Brand实体类型的对象中
        BeanUtils.copyProperties(tagAddNewDTO,tag);
        LocalDateTime time = LocalDateTime.now();
        //补全属性值
        tag.setArticleCount(0);
        tag.setSort(0);
        tag.setGmtCreate(time);

        // 将标签数据写入到数据库中
        log.info("即将向表中写入数据:{}",tag);
        int rows = tagMapper.insert(tag);
        if (rows!=1){
            String message="添加标签失败,服务器忙,请稍后再次尝试";
            log.info(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
    }

    @Override
    public void updateTag(TagAddNewDTO tagAddNewDTO) {
        log.debug("准备开始处理修改标签的业务，参数：{}", tagAddNewDTO);

        if (tagAddNewDTO.getName()!=null){
            if (tagMapper.isName(tagAddNewDTO.getId(),tagAddNewDTO.getName()) > 0) {
                throw new ServiceException(ServiceCode.ERR_CONFLICT, "该标签已被使用！");
            }
        }

        LocalDateTime time = LocalDateTime.now();
        tagAddNewDTO.setGmtModified(time);
        tagAddNewDTO.setGmtModified(LocalDateTime.now());
        if (tagMapper.updateById(tagAddNewDTO) <= 0) {
            throw new ServiceException(ServiceCode.ERR_UPDATE, "修改标签失败,请稍后重试！");
        }
    }

    @Override
    public String deleteByIds(List<Long> list) {
        log.debug("开始处理根据id删除标签业务,参数:{}", list);

//        int counts = bTagMapper.countById(list);
//        log.debug("查询到需要删除的id对应的个数{},未查询到的id对应的个数:{}", counts, (list.size() - counts));

        int rowsTag = tagMapper.deleteByIds(list);
        articleTagMapper.deleteByTagId(list);

        String message = "成功删除标签数量:" + rowsTag + "; 删除失败标签数量:" + (list.size() - rowsTag);
        log.debug(message);
        return message;
    }

    @Override
    public int selectCount() {
        log.info("开始查询标签数量");
        int count = tagMapper.selectCount();
        return count;
    }

    @Override
    public TagDetailVO getById(Long id) {
        log.info("开始查询标签详情");
        TagDetailVO tagDetailVO = tagMapper.getById(id);
        return tagDetailVO;
    }


    @Override
    public List<TagListItemVO> list(Long offset, Long count) {
        log.debug("查询标签列表业务");
        List<TagListItemVO> list = tagMapper.list(offset, count);
        for (TagListItemVO tagListItemVO : list){
            long counts = articleTagMapper.countByTagId(tagListItemVO.getId());
            tagListItemVO.setArticleCount(counts);
        }
        return list;
    }


    /**
     * 前台标签查询
     * @return
     */
    @Override
    public List<TagListItemVO> selectTagList() {
        log.debug("====执行service查询方法====");
        boolean isExpired = tagRepository.isExpired(KEY_PREFIX_Tag_ITEM);
        if (isExpired){
            log.debug("====执行数据库查询存入Redis====");
            List<TagListItemVO> list = tagMapper.selectTagList();
            if (list == null){
                throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"数据库中没有标签");
            }
            tagRepository.putList(list,KEY_PREFIX_Tag_ITEM);
        }
        List<TagListItemVO> tagListItemVOs = tagRepository.getList(KEY_PREFIX_Tag_ITEM);
        return tagListItemVOs;
    }

}
